package org.mobile.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mobile.beans.User;
import org.mobile.logic.UserLogic;

/**
 * Servlet implementation class Register
 */
@WebServlet("/register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String password= request.getParameter("password");
		String retypePass= request.getParameter("repeatpass");
		String name=  new String(request.getParameter("name").getBytes("ISO8859_1"), "UTF-8");
		String surname= new String(request.getParameter("surname").getBytes("ISO8859_1"), "UTF-8");
		String address= new String(request.getParameter("address").getBytes("ISO8859_1"), "UTF-8");
		String login= request.getParameter("login");
		if(!login.isEmpty() && !password.isEmpty() && !surname.isEmpty() && !name.isEmpty() && !address.isEmpty()){
			
			if(password.equals(retypePass)){
				User user= new User();
				user.setLogin(request.getParameter("login"));
				user.setPassword(request.getParameter("password"));
				user.setName(name);
				user.setSurname(surname);
				user.setType("User");
				user.setAddress(address);
				user.setStyle(User.DEFAULT_THEME);
				if(!UserLogic.getInstance().addUser(user)){
					request.setAttribute("error", "Błąd rejestracji!");
					request.getRequestDispatcher("errPage.jsp").forward(request, response);
				}
				else{
					request.setAttribute("message", "Zarejestrowano");
					request.getRequestDispatcher("index.jsp").forward(request, response);
				}
				
			}
			else{
				request.setAttribute("error", "Podane hasła nie zgadzają się!");
				request.getRequestDispatcher("errPage.jsp").forward(request, response);
			}
		}
		else{
			request.setAttribute("error", "Błąd rejestracji, wypełnij wszystkie pola!");
			request.getRequestDispatcher("errPage.jsp").forward(request, response);
		}
	}

}
